package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.service.constant.RedisConstant;
import com.atguigu.common.service.exception.SpzxException;
import com.atguigu.spzx.model.entity.system.SysUserAuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.base.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author yaya
 * @Create 2024/6/21 16:01
 * Description:
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String method = request.getMethod();
        // 预检请求放行
        if (method.equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            throw new SpzxException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        String sysUserJsonStr = redisTemplate.opsForValue().get(RedisConstant.ADMIN_LOGIN_PREFIX + token);
        if (!StringUtils.hasText(sysUserJsonStr)){
            throw new SpzxException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        // 存入线程仓库中
        SysUser sysUser = JSON.parseObject(sysUserJsonStr, SysUser.class);
        SysUserAuthContextUtil.set(sysUser);


        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        SysUserAuthContextUtil.remove();
    }
}
